import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QVBoxLayout, QLabel
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QPixmap

class ObjectMethodDemo(QWidget):
    def __init__(self):
        super().__init__()
        self.init_ui()
        
    def init_ui(self):
        layout = QVBoxLayout()
        
        self.info_label = QLabel('对象方式文件对话框演示')
        self.info_label.setAlignment(Qt.AlignCenter)
        
        custom_btn = QPushButton('自定义文件对话框')
        custom_btn.clicked.connect(self.custom_file_dialog)
        
        layout.addWidget(custom_btn)
        layout.addWidget(self.info_label)
        self.setLayout(layout)
        self.setWindowTitle('对象方式文件对话框')
        
    def custom_file_dialog(self):
        from PyQt5.QtWidgets import QFileDialog
        from PyQt5.QtCore import QDir
        
        # 创建文件对话框对象
        dialog = QFileDialog(self)
        dialog.setWindowTitle('自定义文件对话框')
        dialog.setDirectory(QDir.homePath())  # 设置初始目录为家目录
        dialog.setNameFilter("文本文件 (*.txt);;所有文件 (*)")
        dialog.setFileMode(QFileDialog.AnyFile)  # 可以选择任何文件
        dialog.setViewMode(QFileDialog.Detail)   # 详细视图
        
        # 设置选项
        dialog.setOption(QFileDialog.DontUseNativeDialog, True)  # 不使用系统原生对话框
        dialog.setOption(QFileDialog.ReadOnly, True)
        
        # 连接信号
        dialog.currentChanged.connect(self.on_current_changed)
        dialog.fileSelected.connect(self.on_file_selected)
        
        # 显示对话框
        if dialog.exec_() == QFileDialog.Accepted:
            selected_files = dialog.selectedFiles()
            if selected_files:
                self.info_label.setText(f"选择的文件: {selected_files[0]}")
        else:
            self.info_label.setText("用户取消了选择")
    
    def on_current_changed(self, path):
        """当前选择改变时的回调"""
        print(f"当前选择: {path}")
    
    def on_file_selected(self, file):
        """文件被选择时的回调"""
        print(f"文件被选择: {file}")

            
if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = ObjectMethodDemo()
    window.show()
    sys.exit(app.exec_())